package com.audaque.springboot.foshanupload.session.interceptor;

import com.audaque.springboot.foshanupload.authcore.constants.AuthConst;
import com.audaque.springboot.foshanupload.authcore.model.currentUser.TransmittableThreadLocalCurrentUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @author zgb
 * @desc 已登录则把会话转传到会话域和上下文
 * @date 2022-06-16 18:37:27
 */
//通过配置order()的值，值越小，优先级越高。不配默认是0
@Order(0)
@Slf4j
public class SessionLoginInterceptor implements HandlerInterceptor {


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        TransmittableThreadLocalCurrentUser transmittableThreadLocalCurrentUser = TransmittableThreadLocalCurrentUser.getCurrentUser();
        if (transmittableThreadLocalCurrentUser != null) {
            //登录成功处理
            HttpSession session = request.getSession();
            //spring session负责创建sessionId,开发者处理
            String sessionId = session.getId();
            transmittableThreadLocalCurrentUser.setSessionId(sessionId);
            //共享CURRENT_USER_KEY到session
            session.setAttribute(AuthConst.CURRENT_USER_KEY, transmittableThreadLocalCurrentUser);
        }
        return true;
    }
}
